package javango.contrib.admin.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javango.contrib.admin.ModelManager;
import javango.contrib.hibernate.HibernateUtil;
import javango.contrib.hibernate.ModelDao;

import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;

/**
 * Subclasses should override the constructor calling addClass or addClasses to build the list of classes that can be managed via the admin interface
 * @param clazz
 */
public class CustomAdminOptions implements AdminOptions {

	List<Class> classList = new ArrayList<Class>();
	Map<Class, ModelManager> managers = new HashMap<Class, ModelManager>();
	
	HibernateUtil hibernateUtil;
	
	public CustomAdminOptions(HibernateUtil hibernateUtil) {
		this.hibernateUtil = hibernateUtil;
	}

	protected void addClasses(Class... classes) {
		for(Class c : classes) {
			addClass(c);
		}
	}

	
	protected void addClass(Class clazz) {
		this.classList.add(clazz);
	}
	
	public Class getClassMapping(String entityName) {
		for(Class c : classList) {
			if (c.getName().equals(entityName)) {
				return c;
			}
		}
		return null;
	}

	public Iterator<Class> getClassMappings() {
		return classList.iterator();
	}

	public ModelManager<?> getManager(Class entityClass) {
		if (managers.containsKey(entityClass)) {
			return managers.get(entityClass);
		}
		
		return new javango.contrib.admin.BaseModelManager(entityClass, new ModelDao(hibernateUtil, entityClass));
	}

	public List<String> getFieldList(Class clazz) {
		// TODO Does not verify the class is in the classList
		List<String> property_list = new ArrayList<String>();
		
		Iterator<Property> i = hibernateUtil.getConfiguration().getClassMapping(clazz.getName()).getPropertyIterator();
		while (i.hasNext()) {
			Property p = i.next();
			property_list.add(p.getName());
		}
		return property_list;
	}
}
